﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Drawing.Imaging;
using System.Web.UI.WebControls;
using System.Web;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using System.Drawing;

namespace XUtility
{
    public class ImageClass
    {
        #region 图片转换成Byte[]对象
        #region 根据图片文件的路径使用文件流打开，并保存为Byte[]
        /// <summary>
        /// 根据图片文件的路径使用文件流打开，并保存为Byte[]
        /// <para>路径可以是物理路径，也可以是网址路径,根据是否以 "http" 开头判断</para>
        /// </summary>
        /// <param name="imgPath">图片文件的路径</param>
        /// <returns>图片 二进制</returns>
        public static Byte[] GetImageByte(String imgPath)
        {
            try
            {
                if (imgPath.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                {
                    #region 网址路径
                    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(imgPath);
                    webRequest.Method = "GET";
                    HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                    Stream s = webResponse.GetResponseStream();
                    List<Byte> list = new List<Byte>();

                    while (true)
                    {
                        Int32 data = s.ReadByte();
                        if (data == -1)
                            break;
                        else
                        {
                            Byte b = (Byte)data;
                            list.Add(b);
                        }
                    }
                    Byte[] bb = list.ToArray();
                    //File.WriteAllBytes("C://1.jpg", bb); // 可用以保存到客户端
                    s.Close();

                    return bb;
                    #endregion
                }
                else
                {
                    #region 物理路径
                    FileStream fs = new FileStream(imgPath, FileMode.Open);
                    Byte[] byData = new Byte[fs.Length];
                    fs.Read(byData, 0, byData.Length);
                    fs.Close();

                    return byData;
                    #endregion
                }
            }
            catch (Exception)
            {

                throw;
            }

        }
        #endregion

        #region 将Image对象转换成流数据，并保存为Byte[]
        /// <summary>
        /// 将Image对象转换成流数据，并保存为Byte[]
        /// </summary>
        /// <param name="objImage">图片对象</param>
        /// <returns>图片 二进制</returns>
        public static Byte[] GetImageByte(System.Drawing.Image objImage)
        {
            MemoryStream mstream = new MemoryStream();
            objImage.Save(mstream, ImageFormat.Gif);
            Byte[] byData = new Byte[mstream.Length];
            mstream.Position = 0;
            mstream.Read(byData, 0, byData.Length);
            mstream.Close();

            return byData;
        }

        /// <summary>
        /// 将Image对象转换成流数据，并保存为Byte[]
        /// </summary>
        /// <param name="objImage">Image对象</param>
        /// <param name="imgFormat">图片格式</param>
        /// <returns>图片 二进制</returns>
        public static Byte[] GetImageByte(System.Drawing.Image objImage, ImageFormat imgFormat)
        {
            MemoryStream mstream = new MemoryStream();
            objImage.Save(mstream, imgFormat);
            Byte[] byData = new Byte[mstream.Length];
            mstream.Position = 0;
            mstream.Read(byData, 0, byData.Length);
            mstream.Close();

            return byData;
        }
        #endregion

        #region 通过FileUpload控件获取二进制数据
        /// <summary>
        /// 通过FileUpload控件获取二进制数据
        /// </summary>
        public static Byte[] GetImageByte(FileUpload FileUpload1)
        {
            Stream stream = FileUpload1.PostedFile.InputStream;
            Byte[] photo = new Byte[FileUpload1.PostedFile.ContentLength];
            stream.Read(photo, 0, FileUpload1.PostedFile.ContentLength);
            stream.Close();
            return photo;
        }
        #endregion

        #region 根据ASP.NET中的HttpFileCollection返回的数组遍历HttpPostedFile的方法
        /// <summary>
        /// 根据ASP.NET中的HttpFileCollection返回的数组遍历HttpPostedFile的方法
        /// </summary>
        public static Byte[] GetImageByte(HttpPostedFile httpfile)
        {
            Stream stream = httpfile.InputStream;
            Byte[] photo = new Byte[httpfile.ContentLength];
            stream.Read(photo, 0, httpfile.ContentLength);
            stream.Close();
            return photo;
        }
        #endregion

        #region 将数据库中的Image类型转换成Byte[]
        /// <summary>
        /// 将数据库中的Image类型转换成Byte[]
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="Fleid"></param>
        /// <returns></returns>
        public static Byte[] GetImageByte(SqlDataReader reader, String Fleid)
        {
            return (Byte[])reader[Fleid];//Image为数据库中存放Image类型字段
        }
        #endregion
        #endregion

        #region 将Byte[]转换成Image图像类型
        /// <summary>
        /// 将Byte[]转换成Image图像类型
        /// </summary>
        public static System.Drawing.Image ConvertImage(Byte[] mybyte)
        {
            System.Drawing.Image image;
            MemoryStream mymemorystream = new MemoryStream(mybyte, 0, mybyte.Length);
            image = System.Drawing.Image.FromStream(mymemorystream);
            return image;
        }
        #endregion

        /// <summary>
        /// 生成指定路径文件的缩略图
        /// </summary>
        /// <param name="sFilePath">指定文件的绝对路径</param>
        /// <param name="thumbSaveDirPath">缩略图保存的文件夹绝对路径</param>
        /// <param name="sThumbFileName">缩略图预期的文件名</param>
        /// <param name="intThumbWidth">缩略图宽度</param>
        /// <param name="intThumbHeight">缩略图高度</param>
        /// <returns>生成的缩略图名称</returns>
        public string CreateThumb(string sFilePath, string thumbSaveDirPath, string sThumbFileName, int intThumbWidth, int intThumbHeight)
        {
            try
            {
                //原图加载 
                using (System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(sFilePath))
                {
                    //原图宽度和高度 
                    int width = sourceImage.Width;
                    int height = sourceImage.Height;
                    int smallWidth;
                    int smallHeight;
                    //获取第一张绘制图的大小,(比较 原图的宽/缩略图的宽 和 原图的高/缩略图的高) 
                    if (((decimal)width) / height <= ((decimal)intThumbWidth) / intThumbHeight)
                    {
                        smallWidth = intThumbWidth;
                        smallHeight = intThumbWidth * height / width;
                    }
                    else
                    {
                        smallWidth = intThumbHeight * width / height;
                        smallHeight = intThumbHeight;
                    }
                    //判断缩略图在当前文件夹下是否同名称文件存在 

                    int file_append = 0;
                    string extendName = Path.GetExtension(sFilePath).ToLower();//扩展名
                    string sThumbFilePath = thumbSaveDirPath + sThumbFileName + extendName;
                    while (File.Exists(sThumbFilePath))
                    {
                        file_append++;
                        sThumbFilePath = thumbSaveDirPath + sThumbFileName +
                        file_append.ToString() + extendName;
                    }
                    //缩略图保存的绝对路径 
                    string smallImagePath = sThumbFilePath;//多余的一步
                    //新建一个图板,以最小等比例压缩大小绘制原图 
                    using (System.Drawing.Image bitmap = new System.Drawing.Bitmap(smallWidth, smallHeight))
                    {
                        //绘制中间图 
                        using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
                        {
                            //高清,平滑 
                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                            g.Clear(Color.Black);
                            g.DrawImage(
                            sourceImage,
                            new System.Drawing.Rectangle(0, 0, smallWidth, smallHeight),
                            new System.Drawing.Rectangle(0, 0, width, height),
                            System.Drawing.GraphicsUnit.Pixel
                            );
                        }
                        //新建一个图板,以缩略图大小绘制中间图 
                        using (System.Drawing.Image bitmap1 = new System.Drawing.Bitmap(intThumbWidth, intThumbHeight))
                        {
                            //绘制缩略图 
                            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap1))
                            {
                                //高清,平滑 
                                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                                g.Clear(Color.Black);
                                int lwidth = (smallWidth - intThumbWidth) / 2;
                                int bheight = (smallHeight - intThumbHeight) / 2;
                                g.DrawImage(bitmap, new Rectangle(0, 0, intThumbWidth, intThumbHeight), lwidth, bheight, intThumbWidth, intThumbHeight, GraphicsUnit.Pixel);
                                g.Dispose();
                                bitmap1.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                            }
                        }
                        //返回缩略图名称 
                        return Path.GetFileName(smallImagePath);
                    }
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }



        /// <summary> 
        /// jpeg图片质量压缩 
        /// </summary> 
        /// <param name="sFile">文件原地址</param> 
        /// <param name="outPath">文件输出地址</param> 
        /// <param name="flag">压缩级别1-100 </param> 
        /// <returns></returns> 
        public static bool GetPicThumbnail(string sFile, string outPath, int flag)
        {
            System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
            ImageFormat tFormat = iSource.RawFormat;
            //以下代码为保存图片时，设置压缩质量 
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100 
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    iSource.Save(outPath, jpegICIinfo, ep);//dFile是压缩后的新路径 
                }
                else
                {
                    iSource.Save(outPath, tFormat);
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
                iSource.Dispose();
            }
        }
    }
}
